/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.bff.engine.api.resource;

import com.inspur.edp.bef.bizentity.GspBizEntityElement;
import com.inspur.edp.bef.bizentity.GspBizEntityObject;
import com.inspur.edp.bff.spi.builtin.BffEntityResInfoImpl;
import com.inspur.edp.cef.designtime.api.IGspCommonField;
import com.inspur.edp.cef.designtime.api.element.GspElementObjectType;
import com.inspur.edp.cef.entity.condition.SortCondition;
import com.inspur.edp.cef.spi.entity.resourceInfo.builinImpls.CefModelResInfoImpl;
import com.inspur.edp.das.commonmodel.IGspCommonElement;
import com.inspur.edp.das.commonmodel.IGspCommonObject;
import com.inspur.edp.formserver.viewmodel.GspViewModel;
import com.inspur.edp.formserver.viewmodel.GspViewModelElement;
import com.inspur.edp.formserver.viewmodel.GspViewObject;
import io.iec.edp.caf.common.JSONSerializer;
import org.springframework.util.StringUtils;

import java.util.List;

public class BffEngineEntityResourceInfo extends BffEntityResInfoImpl {

  private GspViewObject obj;
  private BffEngineModelResInfo modelResInfo;
  private GspBizEntityObject beObject;

  public BffEngineEntityResourceInfo(GspViewObject obj,BffEngineModelResInfo modelResInfo,
      GspBizEntityObject beObject) {
    super(obj.getCode(),obj.getI18nResourceInfoPrefix()+".Name",modelResInfo,modelResInfo.getVo().getID());
    this.obj = obj;
    this.modelResInfo = modelResInfo;
    this.beObject = beObject;
    initColumns1();
    initSorts();
    initChildInfos1(modelResInfo);
  }

  /**
   * 初始化排序条件
   */
  private void initSorts() {
    if(StringUtils.isEmpty(obj.getOrderbyCondition()))
      return;
    List<SortCondition> sorts;
    try {
      sorts = JSONSerializer.deserialize(obj.getOrderbyCondition(), List.class, SortCondition.class);
    } catch (Exception e) {
      throw new RuntimeException(
              obj.getBelongModel() != null ? obj.getBelongModel().getCode()
                      : "" + "节点" + obj.getCode() + "定义的排序条件格式不正确, 请检查", e);
    }
    if(sorts != null && !sorts.isEmpty()) {
      sorts.stream().forEach(sort -> {
        IGspCommonElement element = obj.getElementByLabelId(sort.getSortField());
        if(element == null) {
          throw new RuntimeException("模型" + obj.getBelongModel().getCode() + "的节点" + obj.getCode() + "上设置的排序字段" + sort.getSortField() + "不存在, 请重新设置排序字段.");
        }
        if(element.getParentAssociation() != null) {
          sort.setSortField(element.getParentAssociation().getBelongElement().getLabelID() + "." + element.getLabelID());
        }
      });
      setSorts(sorts);
    }
  }

  @Override
  public boolean isRoot() {
    return obj.isRootNode();
  }

  /**
   * 初始化列信息
   */
  protected void initColumns1() {
    super.initColumns();
    for (IGspCommonField field : obj.getContainElements()) {
      if(field.getObjectType() == GspElementObjectType.Association && (field.getChildAssociations() ==null
          || field.getChildAssociations().size() == 0)){
        continue;
      }
      GspViewModelElement voElement = (GspViewModelElement)field;
      if(field.getIsVirtual() || beObject == null){
        addPropertyInfo(new BffEnginePropInfoGenerator().getDataTypePropertyInfo(voElement, null));
        continue;
      }
      IGspCommonElement beField = beObject.findElement(voElement.getMapping().getTargetElementId());
      addPropertyInfo(new BffEnginePropInfoGenerator().getDataTypePropertyInfo(voElement, beField == null ? null: (GspBizEntityElement)beField));
    }
  }

  @Override
  public String getConfigId() {
    return obj.getBelongModel().getGeneratedConfigID();
  }

  /**
   * 获取子级信息
   * @param modelResInfo
   */
  protected void initChildInfos1(CefModelResInfoImpl modelResInfo) {
    if(obj.getContainChildObjects()==null||obj.getContainChildObjects().size()==0)
      return;
    for(IGspCommonObject childObj:obj.getContainChildObjects())
    {
      addChildEntityResInfo(new BffEngineEntityResourceInfo((GspViewObject) childObj,
          (BffEngineModelResInfo) modelResInfo,findChildBeObject((GspViewObject)childObj)));
    }
  }

  private GspBizEntityObject findChildBeObject(GspViewObject childObj) {
    if (beObject == null)
      return null;
    if(childObj.getIsVirtual())
      return  null;
    return (GspBizEntityObject) beObject.getChildObjectById(childObj.getMapping().getTargetObjId());
  }
    public GspViewObject getViewObject() {
        return this.obj;
    }


    public GspBizEntityObject getBizEntityObject() {
        return this.beObject;
    }
}
